# -*- coding: utf-8 -*-
#
# File: Install.py
#
# Copyright (c) 2007 by LM
# Generator: ArchGenXML Version 1.5.1 svn/devel
#            http://plone.org/products/archgenxml
#
# GNU General Public License (GPL)
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301, USA.
#

__author__ = """LM <leonardo.mirandas@gmail.com>"""
__docformat__ = 'plaintext'

from StringIO import StringIO
from Products.CMFCore.utils import getToolByName
from Products.GrupoVisao.content.vocabularies import *
from Products.GrupoVisao.config import *
from Products.GrupoVisao.AppConfig import *
#from Products.GrupoVisao.Extensions.install_taxonomy import *
from Products.ExternalMethod.ExternalMethod import ExternalMethod
from Products.CMFPlone.migrations.migration_util import safeEditProperty

INDEX_HTML = '''
<html metal:use-macro="here/main_template/macros/master">
    <div metal:fill-slot="content">
        <hr class="tamanho">
        <div metal:use-macro="here/portlet_banners/macros/portlet">
            banners
        </div>

        <div metal:use-macro="here/portlet_destaques/macros/portlet">
            texto informativo do hospital
        </div>

    </div>
</html>
'''

def replaceIndex(portal, out):
    print >> out, "Installation index_html"  
 
    if 'front-page' in portal.objectIds():
       portal.manage_delObjects('front-page')

    if 'index_html' in portal.objectIds():
       portal.manage_delObjects('index_html')

    portal.manage_addProduct['PageTemplates'].manage_addPageTemplate('index_html', '', INDEX_HTML)

def setupPortal(portal, out):
    print >> out, "Installation properties"
    portal.manage_changeProperties(title='VISÃO INSTITUTOS',
                                   email_from_address='contato@visaoinstitutos.com.br',
                                   email_from_name= 'Contato')

def setupFolders(portal, out):
    print >> out, "Installation structure"

    portal_workflow = getToolByName(portal, 'portal_workflow')
    portal_types = getToolByName(portal, 'portal_types')
    addable_types=['Document','Image','Folder','File']

    #apgar
    portal_types['Plone Site'].filter_content_types = False

    #create folders
    if 'quem_somos' not in portal.objectIds():
        portal.invokeFactory('Folder', id='quem_somos', title='Quem somos', excludeFromNav=0)
        quem_somos = getattr(portal, 'quem_somos')
        portal_workflow.doActionFor(quem_somos, 'publish')

    if 'servicos' not in portal.objectIds():
        portal.invokeFactory('Folder', id='servicos', title='Servicos', excludeFromNav=0)
        servicos = getattr(portal, 'servicos')
        portal_workflow.doActionFor(servicos, 'publish')

    if 'convenios' not in portal.objectIds():
        portal.invokeFactory('Folder', id='convenios', title='Convenios', excludeFromNav=0)
        convenios = getattr(portal, 'convenios')
        portal_workflow.doActionFor(convenios, 'publish')

    if 'patologias' not in portal.objectIds():
        portal.invokeFactory('Folder', id='patologias', title='Patologias', excludeFromNav=0)
        patologias = getattr(portal, 'patologias')
        portal_workflow.doActionFor(patologias, 'publish')

    if 'fique_de_olho' not in portal.objectIds():
        portal.invokeFactory('folder_jornais', id='fique_de_olho', title='Fique de Olho', excludeFromNav=0)
        fique_de_olho = getattr(portal, 'fique_de_olho')
        portal_workflow.doActionFor(fique_de_olho, 'publish')

    if 'imprensa' not in portal.objectIds():
        portal.invokeFactory('Folder', id='imprensa', title='Imprensa', excludeFromNav=0)
        imprensa = getattr(portal, 'imprensa')
        portal_workflow.doActionFor(imprensa, 'publish')

    if 'noticias' not in portal.objectIds():
        portal.invokeFactory('folder_noticias', id='noticias', title='Noticias', excludeFromNav=0)
        noticias = getattr(portal, 'noticias')
        portal_workflow.doActionFor(noticias, 'publish')

    if 'banners' not in portal.objectIds():
        portal.invokeFactory('folder_banners', id='banners', title='Banners', excludeFromNav=0)

    if 'destaques' not in portal.objectIds():
        portal.invokeFactory('folder_destaques', id='destaques', title='Destaques', excludeFromNav=0)

    if 'recursos_humanos' not in portal.objectIds():
        portal.invokeFactory('folder_rh', id='recursos_humanos', title='Recursos Humanos', excludeFromNav=0)

   #if 'recursos_humanos' not in portal.objectIds():
       #portal.invokeFactory('folder_recursos_humanos', id='Recursos Humanos', title='Recursos Humanos', excludeFromNav=0)
       #recursos_humanos = getattr(portal, 'recursos_humanos')
       #portal_workflow.doActionFor(recursos_humanos, 'publish')

    if 'area_cientifica' not in portal.objectIds():
        portal.invokeFactory('folder_area_cientifica', id='area_cientifica', title='Area Cientifica', excludeFromNav=0)
        area_cientifica = getattr(portal, 'area_cientifica')
        portal_workflow.doActionFor(area_cientifica, 'publish')
        
        if 'programacao_da_semana' not in area_cientifica.objectIds():
            area_cientifica.invokeFactory('folder_programacao_cientifica', id='programacao_da_semana', title='Programação da Semana', excludeFromNav=0)

        if 'resultado_das_provas' not in area_cientifica.objectIds():
            area_cientifica.invokeFactory('folder_resultado_provas', id='resultado_das_provas', title='Resultado das Provas', excludeFromNav=0)

        if 'publicacoes_de_trabalho' not in area_cientifica.objectIds():
            area_cientifica.invokeFactory('folder_publicacoes_cientifica', id='publicacoes_de_trabalho', title='Publicações de Trabalho', excludeFromNav=0)

        if 'banners_cientificos' not in area_cientifica.objectIds():
            area_cientifica.invokeFactory('folder_banner_cientifico', id='banners_cientificos', title='Vídeos Cientificos', excludeFromNav=0)
            banners_cientificos = getattr(area_cientifica, 'banners_cientificos')
            portal_workflow.doActionFor(banners_cientificos, 'Publicar')

        if 'informes_medicos' not in area_cientifica.objectIds():
            area_cientifica.invokeFactory('folder_informe_cientifico', id='informes_medicos', title='Informe Médico', excludeFromNav=0)
     
        #desabilita inserir novas pastas
        portal_types['folder_area_cientifica'].filter_content_types = True
        portal_types['folder_area_cientifica'].allowed_content_types = []
        
        #modifica as permissoes
        area_cientifica.manage_permission('Modify portal content' ,['Manager', 'AdmCientifico'],False)
        area_cientifica.manage_permission('GrupoVisao: Add banner_cientifico' ,['Manager', 'AdmCientifico'],False)
        area_cientifica.manage_permission('Add portal content' ,['Manager', 'AdmCientifico'],False)        

    portal_types['Plone Site'].filter_content_types = True
    portal_types['Plone Site'].allowed_content_types = []

    portal_types['Folder'].filter_content_types = True
    portal_types['Folder'].allowed_content_types = addable_types


def deletePastas(portal, out):
    print >> out, "delete documents"
    if 'news' in portal.objectIds():
       portal.manage_delObjects('news')
    if 'events' in portal.objectIds():
       portal.manage_delObjects('events')

def setupSkin(portal, out):
    print >> out, "Installation skin"
    portal_skins = getToolByName(portal, 'portal_skins')
    path = portal_skins.getSkinPath('Plone Default')
    path = [elem.strip() for elem in path.split(',') if elem != '.svn']
    path = ','.join(path)
    portal_skins.addSkinSelection('Portal Grupo Visao', path)
    portal_skins.manage_properties(default_skin = 'Portal Grupo Visao',
			           request_varname = 'plone_skin',
			           del_skin = 0, 
                                   chosen = [])

def addCSS(portal, out):
    print >> out, "Installation style"
    portal.portal_css.manage_addStylesheet(id='grupoVisaoCustom.css',
                                               expression='',
                                               media='screen',
                                               rel='sylesheet',
                                               title='',
                                               rendering='import',
                                               enabled=True,
                                               cookable=True,
                                               REQUEST=None,)

def setupPortlet(portal, out):
    print >> out, "Installation portlets"
    #add portlet in left_slots
    left_slots=()

    #add portlet in right_slots
    right_slots=( 'here/portlet_busca/macros/portlet'
                , 'here/portlet_noticias/macros/portlet' 
                , 'here/portlet_adm/macros/portlet' )

    safeEditProperty(portal, 'left_slots', left_slots)
    safeEditProperty(portal, 'right_slots', right_slots)

#def setVisaoProperties(portal,out):
    #print >> out, "Installation Properties"
    #portal_properties = getToolByName(portal, 'portal_properties')
    #if not hasattr(portal_properties,'visao_portal_properties'):
       #portal_properties.manage_addPropertySheet('visao_portal_properties','Propriedades do Portal do Grupo Visao')

    ##for vocab in VOCABULARIOS.keys():
    #if not portal_properties.visao_portal_properties.hasProperty('vocab_estados'):
        #portal_properties.visao_portal_properties._setProperty('vocab_estados', VOCAB_ESTADOS, 'lines')

PERMISSION_LIST = (
    {
        'permission' : 'GrupoVisao: View Area Cientifica',
        'roles' : ['Manager','MembroCientifico','AdmCientifico'],
        'acquire' : False,
    },

    {
        'permission' : 'GrupoVisao: View Campanhas',
        'roles' : ['Manager','MembroCampanha'],
        'acquire' : False,
    },

)

def setupPermissions(portal, out):
    print >> out, "Installation security"
    for p in PERMISSION_LIST:
        portal.manage_permission(p['permission'], roles=p['roles'], acquire=p['acquire'])

def setupRoles(portal, out):
    print >> out, "Installation roles" 
    portal._addRole('MembroCampanha')
    portal._addRole('AdmCientifico')
    portal._addRole('MembroCientifico')

def install(self):
    out = StringIO()
    portal = self
    replaceIndex(portal, out)
    setupRoles(portal, out)
    setupPermissions(portal, out)
    setupFolders (portal, out)
    deletePastas(portal, out)
    setupPortal(portal, out)
    setupSkin(portal, out)
    addCSS(portal, out)
    setupPortlet(portal, out)
    #setVisaoProperties(portal, out)

def uninstall(self):
    portal = self
    portal_types = getToolByName(portal, 'portal_types')
    portal_types['Plone Site'].global_allow = True
    portal_types['Plone Site'].filter_content_types = False